//
//  CYHomeViewController.m
//  cyjf
//
//  Created by tauCross on 2017/5/3.
//  Copyright © 2017年 Auto Financing. All rights reserved.
//

#import "CYHomeViewController.h"

#import "CYHomeBannerCell.h"
#import "CYHomeRecommendCell.h"
#import "CYHomeSafeCell.h"
#import "CYHomeNewsTitleCell.h"
#import "CYHomeNewsFooterCell.h"
#import "CYHomeNewsCell.h"
#import "CYEmptyCell.h"

#import "CYFinanceDetailViewController.h"
#import "CYNewsViewController.h"
#import "CYWebViewController.h"
#import "CYMainController.h"

#import "CYActionManager.h"

#import "CYDataAPINewsModel.h"

#import <UIScrollView+TCRefresh.h>


#import "CYShareManager.h"



@interface CYHomeViewController ()

@property(nonatomic, strong)CYHomeBannerCellObject *bannerCell;
@property(nonatomic, strong)CYHomeRecommendCellObject *recommendCell;
@property(nonatomic, strong)CYHomeSafeCellObject *safeCell;
@property(nonatomic, strong)NICellObject *newsTitleCell;
@property(nonatomic, strong)NSMutableArray<CYHomeNewsCellObject *> *newsCells;
@property(nonatomic, strong)NICellObject *newsFooterCell;

@property(nonatomic, strong)NSMutableArray *resluts;
@property(nonatomic, assign)NSInteger refreshAPICount;

@end



@implementation CYHomeViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self loadDataFromServer];
}

- (void)loadUI
{
    self.tableView.tableFooterView = [self createTableFooter];
    self.tableView.tableFooterView.hidden = YES;
    
    @weakify(self);
    [self.tableView setupRefreshWithBottomAt:0 refreshBlock:^{
        @strongify(self);
        [self loadDataFromServer];
    }];
}

- (void)loadCells
{
    @weakify(self);
    self.bannerCell = [CYHomeBannerCellObject objectWithCellClass:[CYHomeBannerCell class]];
    self.bannerCell.onClickBannerBlock = ^(CYDataAPIActionModel *actionModel) {
        @strongify(self);
        [self bannerActionWithActionModel:actionModel];
    };
    self.bannerCell.onClickNoticeBlock = ^(CYDataAPIMessageModel *messageModel) {
        @strongify(self);
        [self bannerActionWithNoticeModel:messageModel];
    };

    self.recommendCell = [CYHomeRecommendCellObject objectWithCellClass:[CYHomeRecommendCell class]];
    self.recommendCell.investAction = ^{
        @strongify(self);
        [self investAction];
    };

    self.safeCell = [CYHomeSafeCellObject objectWithCellClass:[CYHomeSafeCell class]];
    
    self.newsTitleCell = [NICellObject objectWithCellClass:[CYHomeNewsTitleCell class]];
    
    self.newsCells = [NSMutableArray array];
    
    self.newsFooterCell = [NICellObject objectWithCellClass:[CYHomeNewsFooterCell class]];
}

- (void)reloadTableView
{
    {
        NSMutableArray *cells = [NSMutableArray array];
        {
            [cells addObject:self.bannerCell];
        }
        {
            CYEmptyCellObject *cell = [CYEmptyCellObject objectWithCellClass:[CYEmptyCell class]];
            cell.height = 10;
            [cells addObject:cell];
        }
        {
            [cells addObject:self.recommendCell];
        }
        {
            CYEmptyCellObject *cell = [CYEmptyCellObject objectWithCellClass:[CYEmptyCell class]];
            cell.height = 10;
            [cells addObject:cell];
        }
        {
            [cells addObject:self.safeCell];
        }
        if(self.newsCells.count)
        {
            {
                CYEmptyCellObject *cell = [CYEmptyCellObject objectWithCellClass:[CYEmptyCell class]];
                cell.height = 10;
                [cells addObject:cell];
            }
            {
                [cells addObject:self.newsTitleCell];
            }
            {
                [cells addObjectsFromArray:self.newsCells];
            }
            {
                [cells addObject:self.newsFooterCell];
            }
        }
        self.tableModel = [[NIMutableTableViewModel alloc] initWithSectionedArray:cells delegate:(id)[NICellFactory class]];
        self.tableView.dataSource = self.tableModel;
        [self.tableView reloadData];
    }

}

- (void)loadData
{
    self.resluts = [NSMutableArray array];
    self.refreshAPICount = 0;
    
    [self loadCells];
}

- (void)loadDataFromServer
{
    if(self.resluts.count < self.refreshAPICount)
    {
        return;
    }
    self.refreshAPICount = 4;
    [self.resluts removeAllObjects];
    
    @weakify(self);

    [CYStandardDataAPI news_getTopTwoListWithComplete:^(CYResponse *response) {
        @strongify(self);
        [self.resluts addObject:response];
        if(response.code == 0)
        {
            [self.newsCells removeAllObjects];
            NSArray *newsModels = [CYDataAPINewsModel mj_objectArrayWithKeyValuesArray:response.content];
            for(CYDataAPINewsModel *model in newsModels)
            {
                CYHomeNewsCellObject *cell = [CYHomeNewsCellObject objectWithCellClass:[CYHomeNewsCell class]];
                cell.title = SAFE_STRING(model.title);
                cell.source = SAFE_STRING(model.source);
                cell.thumb = SAFE_STRING(model.smallImg);
                cell.id = SAFE_NUMBER(model.id);
                [self.newsCells addObject:cell];
            }
            [self.newsCells.lastObject setIsBottom:YES];
        }
        [self checkAllComplete];
    }];
    
    [CYStandardDataAPI message_bannerListWithPosition:CYDataAPIBannerPositionHome complete:^(CYResponse *response) {
        @strongify(self);
        [self.resluts addObject:response];
        if(response.code == 0)
        {
            NSArray *models = [CYDataAPIBannerModel mj_objectArrayWithKeyValuesArray:response.content];
            self.bannerCell.bannerModels = models;
        }
        [self checkAllComplete];
    }];
    
    [CYStandardDataAPI project_queryRecommendProjectWithComplete:^(CYResponse *response) {
        @strongify(self);
        [self.resluts addObject:response];
        if(response.code == 0)
        {
            self.recommendCell.model = [CYDataAPIRecommendProjectModel mj_objectWithKeyValues:response.content];
        }
        [self checkAllComplete];
    }];
    
    [CYStandardDataAPI advertisement_index_navWithComplete:^(CYResponse *response) {
        @strongify(self);
        [self.resluts addObject:response];
        if(response.code == 0)
        {
            if([response.content[@"nav"] isKindOfClass:[NSArray class]])
            {
                self.bannerCell.itemModels = [CYDataAPIAdvertisementModel mj_objectArrayWithKeyValuesArray:response.content[@"nav"]];
            }
            if([response.content[@"notice"] isKindOfClass:[NSArray class]])
            {
                if([response.content[@"notice"] count] > 0)
                {
                    self.bannerCell.noticeModel = [CYDataAPIMessageModel mj_objectWithKeyValues:[response.content[@"notice"] firstObject]];
                }
                else
                {
                    self.bannerCell.noticeModel = nil;
                }
            }
        }
        [self checkAllComplete];
    }];
}

- (BOOL)prefersNavigationBarHidden
{
    return YES;
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (void)onReceiveApplicationDidBecomeActiveNotification
{
    [self loadDataFromServer];
}

#pragma mark - Actions
- (void)bannerActionWithActionModel:(CYDataAPIActionModel *)model
{
    [CYStandardActionManager executeActionWithModel:model fromViewController:self];
}

- (void)bannerActionWithNoticeModel:(CYDataAPIMessageModel *)model
{
    CYWebViewController *webViewController = [[CYWebViewController alloc] init];
    webViewController.url = [CY_H5_BASE_URL stringByAppendingFormat:@"views/notice.html?id=%@", model.id];
    [self.navigationController pushViewController:webViewController animated:YES];
}

- (void)safeguardsAction
{
    CYWebViewController *webViewController = [[CYWebViewController alloc] init];
    webViewController.url = [CY_H5_BASE_URL stringByAppendingString:@"views/know_us.html"];
    [self.navigationController pushViewController:webViewController animated:YES];
}

- (void)investAction
{
    CYFinanceDetailViewController *financeDetailViewController = [[CYFinanceDetailViewController alloc] init];
    financeDetailViewController.fid = SAFE_NUMBER(self.recommendCell.model.fid);
    [self.navigationController pushViewController:financeDetailViewController animated:YES];
}

- (void)newsListAction
{
    CYNewsViewController *newsViewController = [[CYNewsViewController alloc] init];
    [self.navigationController pushViewController:newsViewController animated:YES];
}

- (void)newsActionWithNewsId:(NSNumber *)id
{
    CYWebViewController *webViewController = [[CYWebViewController alloc] init];
    webViewController.url = [CY_H5_BASE_URL stringByAppendingFormat:@"views/news.html?id=%@", id];
    [self.navigationController pushViewController:webViewController animated:YES];
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    id cellObject = [self.tableModel objectAtIndexPath:indexPath];
    if(cellObject == self.safeCell)
    {
        [MobClick event:UM_EVENT_0014];
        [self safeguardsAction];
        return;
    }
    if(cellObject == self.newsFooterCell)
    {
        [MobClick event:UM_EVENT_0016];
        [self newsListAction];
        return;
    }
    if([cellObject isKindOfClass:[CYHomeNewsCellObject class]])
    {
        [MobClick event:UM_EVENT_0015 label:[(CYHomeNewsCellObject *)cellObject id].stringValue];
        [self newsActionWithNewsId:[(CYHomeNewsCellObject *)cellObject id]];
        return;
    }
}

#pragma mark - Private Method
- (void)checkAllComplete
{
    [self reloadTableView];
    self.tableView.tableFooterView.hidden = NO;
    if(self.resluts.count < self.refreshAPICount)
    {
        return;
    }
    if([self.tableView isRefreshing])
    {
        for(CYResponse *response in self.resluts)
        {
            if(response.code != 0)
            {
                [SVProgressHUD showErrorWithStatus:response.message];
            }
            break;
        }
        [self.resluts removeAllObjects];
    }
    self.refreshAPICount = 0;
    @weakify(self);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        @strongify(self);
        [self.tableView endRefresh];
    });
}

- (UIView *)createTableFooter
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 141)];
    
    UIView *item1 = [self tablefooterItemWithImage:CYImage(@"ico_index_bottom_subject") text1:@"标的真实" text2:@"资金透明"];
    UIView *item2 = [self tablefooterItemWithImage:CYImage(@"ico_index_bottom_safe") text1:@"严格风控" text2:@"安全保障"];
    UIView *item3 = [self tablefooterItemWithImage:CYImage(@"ico_index_bottom_bank") text1:@"晋商银行" text2:@"资金存管"];
    [view addSubview:item1];
    [view addSubview:item2];
    [view addSubview:item3];
    item1.centerY = item2.centerY = item3.centerY = 49;
    item1.centerX = (view.width - 40) / 6 + 20;
    item2.centerX = (view.width - 40) * 3 / 6 + 20;
    item3.centerX = (view.width - 40) * 5 / 6 + 20;
    
    UILabel *label = [[UILabel alloc] init];
    label.text = @"-  汽车行业的未来银行  -";
    label.font = [UIFont systemFontOfSize:12];
    label.textColor = HEXCOLOR(@"CCCCCC");
    [label sizeToFit];
    label.centerX = view.width / 2;
    label.centerY = 93.5;
    [view addSubview:label];
    
    return view;
}

- (UIView *)tablefooterItemWithImage:(UIImage *)image text1:(NSString *)text1 text2:(NSString *)text2
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 90, 50)];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    imageView.image = image;
    imageView.centerY = view.height / 2;
    imageView.left = 10;
    [view addSubview:imageView];
    
    UILabel *label1 = [[UILabel alloc] init];
    label1.text = text1;
    label1.font = [UIFont systemFontOfSize:10];
    label1.textColor = HEXCOLOR(@"CCCCCC");
    [label1 sizeToFit];
    label1.centerY = imageView.top + 7;
    label1.left = imageView.right + 5;
    [view addSubview:label1];
    
    UILabel *label2 = [[UILabel alloc] init];
    label2.text = text2;
    label2.font = [UIFont systemFontOfSize:10];
    label2.textColor = HEXCOLOR(@"CCCCCC");
    [label2 sizeToFit];
    label2.centerY = imageView.bottom - 9;
    label2.left = imageView.right + 5;
    [view addSubview:label2];

    return view;
}

@end
